﻿using System;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using MiddleMvcTask.Data;
using MiddleMvcTask.Data.DataModels;
using System.Collections.Generic;

namespace MiddleMVCTask.Data
{
    public class UserRepository : IRepository<User> 
    {
        protected XDocument Document { get; set; }

        /// <summary>
        /// Represent the absolute path to xml file
        /// </summary>
        protected string Path { get; set; }
        
        public UserRepository() : this("~/App_Data/Users.xml")
        {
        }
        
        /// <summary>
        /// Create instance of UserRepository
        /// </summary>
        /// <param name="fileName"></param>
        public UserRepository(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentException("An instance of fileName is required to use this repository.", "fileName");
            }

            var path = HttpContext.Current.Server.MapPath(fileName);
            this.Document = XDocument.Load(path);
            this.Path = path;
        }
        
        /// <summary>
        /// Return all registered users from xml file
        /// </summary>
        /// <returns></returns>
        public ICollection<User> All()
        {
            var users = from el in Document.Descendants("user")
                        select new User()
                        {
                            Username = el.Attribute("name").Value,
                            Password = el.Attribute("password").Value
                        };

            return users.ToList();
        }

        /// <summary>
        /// Add new user to xml
        /// </summary>
        /// <param name="entity"> new user data model</param>
        /// <returns></returns>
        public User Add(User entity)
        {
            var root = Document.Document.Element("rootElement");

            root.Add(new XElement("user",
                new XAttribute("name", entity.Username),
                new XAttribute("password", entity.Password)));

            return entity;
        }

        /// <summary>
        /// Save new data to xml 
        /// </summary>
        public void Save()
        {
            this.Document.Save(Path);
        }
    }
}